<?php
namespace control;

class fileUploadClass extends adIndexClass
{

    public static function icon($data)
    {
        //参数准备
        $html = "";
        $para = array(
            "download" => "下载",
            "preview" => "文档预览",
            "img" => "图片预览"
        );
        //循环
        foreach ($data as $name => $array) {
            //标题
            $title = (empty($array['title'])) ? ($para[$name] ?? null) : $array['title'];
            if (empty($array)) {
                continue;
            }
            if ($name == "download") {
                if (!empty($array['href'])) {
                    $html .= "\n<a target='_blank' href='" . root . $array['href'] . "' download='" . $array['name'] . "' title='" . $title . "'><img  alt='' src='" . root . "img/control/download.svg' class='listIco'></a>";
                }
            } elseif ($name == "preview") {
                if (!empty($array['href'])) {
                    $url  = self::wps($array);
                    $html .= "\n<a target='_blank' href='" . $url . "' title='" . $title . "'><img alt='' src='" . root . "img/control/preview.svg' class='listIco'></a>";
                }
            } elseif ($name == "img") {
                if (!empty($array['href'])) {
                    $html .= "\n<a target='_blank' href='" . root . $array['href'] . "?time=" . time() . "'><img alt='' src='" . root . "img/control/img.svg' title='" . $title . "' class='listIco'></a>";
                }
            } elseif (array_key_exists($name, $para)) {
                $html .= "\n<img onclick=\"" . $array['click'] . "\" title='" . $title . "' src='" . root . "img/control/" . $name . ".svg' class='listIco'>";
            }
        }
        //返回
        return $html;
    }
    /**
     * @param $id
     * @param string $type
     * @return string
     */
    public static function showSingFile($id,$type=''): string
    {
        $where = $type ? " and target = '$type'" : '';
        $file = query('file', "targetId = '$id' and targetId !='' " . $where);
        $dominate = array(
            "download" => array("name" => $file['name'], "href" => $file['src']),
        );
        if (in_array($file['format'], array("doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf"))) {
            $dominate['preview'] = array("format" => $file['format'], "name" => $file['name'], "href" => $file['src']);
        } elseif (in_array($file['format'], array("png", "gif", "jpg"))) {
            $dominate['img'] = array("title" => "在线预览", "href" => $file['src']);
        }
        return "<span class='del-row-button'>{$file['name']}</span>". self::icon($dominate);

    }
    /**
     * 单个文件上传组件
     */
    public static function singleUpload($formName, $power, $id, $type): string
    {
        $where = $type ? " and target = '$type'" : '';
        /*******附件****************/
        $file = query('file', "targetId = '$id' and targetId !='' " . $where);
        $fileCollection = $file['name'];
        if (empty($file['id'])) {
            //显示上传按钮
            $src = root . 'img/control/upload.svg';
            $direct = 'add';
        } else {
            //显示删除按钮
            $src = root . 'img/control/delete.svg';
            $direct = 'delete';
        }
        return "<div><span id='singFileName' class='del-row-button'>{$fileCollection}</span> <img data-type='$direct' onclick=\"button_method(this,'$power')\"  id='upload-ico' src='$src' style='width: 22px;height: 22px;margin-left: 5px;cursor: pointer' alt=''/>" . hidden(array('name' => 'fileId', 'value' => $file['id'])) .hidden(array('name' => 'targetId', 'value' => $id)) . "</div>
                <div class='hidden'><input name='fileType' value='{$type}'><input name='uploadFile' id='uploadFile' type='file' onchange=\"uploadSingleFile('$formName',root+'control/adIndex.html?cla=fileUpload&fun=uploadSingleFile&power={$power}')\"></div>";
    }

    /**
     * 单个文件保存
     */
    public function uploadSingleFile(): bool|string
    {
        $file = $_FILES['uploadFile'] ?? [];
        $power = $this->get('power');
        $type = $this->post('fileType');
        $id = $this->post('targetId');
        if (!$this->power($power, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($type)) {
            $json['warn'] = '未找到上传的类型';
        } else {
            $result = $this->saveFile($file, $power, explode(',', para('fileFormat')));
            if (!$result['code']) {
                $json['warn'] = $result['warn'];
            } else {
                $file = query('file', "target = '$type' and targetId = '$id'");
                if (empty($file['id'])) {
                    $field = array('id' => suiji(), 'stid' => $this->control['stid'], 'target' => $type, 'name' => $result['fileName'], 'format' => $result['suffix'], 'size' => $result['size'], 'src' => $result['src']);
                    $warn = static::insert(array('table' => 'file', 'field' => $field));
                } else {
                    $field = array('name' => $result['fileName'], 'format' => $result['suffix'], 'size' => $result['size'], 'src' => $result['src']);
                    $warn = static::update(array('table' => 'file', 'where'=>"id = '$file[id]'",'field' => $field));
                    $field['id'] = $file['id'];
                }
                if (in_array($warn, ['新增成功', '更新成功'])) {
                    $json['warn'] = 2;
                    $json['data']['id'] = $field['id'];
                    $json['data']['src'] = root . $field['src'];
                    $json['data']['name'] = $field['name'];
                } else {
                    $json['warn'] = '上传失败';
                }
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 上传图片
     *
     * @param        $id
     * @param string $type
     * @param string $power
     * @param string $formName
     * @return string
     */
    public static function addImgComponent($id, string $type, string $power, string $formName): string
    {
        $root = root;
        $fileCollection = '';
        $result = find(array('table' => "file", 'where' => "targetId !='' and targetId = '{$id}' and target='{$type}' order by time asc"));
        foreach ($result['array'] as $array) {
            $fileCollection .= <<<efo
 <li><img class="li-ico" alt="" src="{$root}{$array['src']}"><a onclick="del_img('{$array['id']}','{$power}',this)" href='javascript:void(0)'><div><span class='u-icon-delete'><i></i></span></div></a></li>
efo;
        }
        return <<<eof
 <div class='img-list'>
 <ul class="img-ul">{$fileCollection}<li id="add-img-btn" ><div title="上传图片"  onclick="$('#uploadImg').click();"  class="add-img-btn">+</div></li></ul>
                     <div class='hidden'><input name='imgType' value='{$type}'><input name='uploadImg' id='uploadImg' accept="image/*" type='file' onchange="uploadAttachFile('{$formName}',root+'control/adIndex.html?cla=fileUpload&fun=uploadImg&power={$power}','add-img-btn')"></div>
</div>
<script>
function del_img(id,power,e){
     let url = root + "control/adIndex.html?cla=fileUpload&fun=delFile";
    $.post(url, {
        id: id,
        power: power
    }, function (res) {
        if (res.warn === 2) {
            $(e).parent().remove();
        } else {
            warn(res.warn);
        }
    }, 'json')
}
</script>
<style>

</style>
eof;
    }

    /**
     * 文件添加组件
     *
     * @param $id       string 对象ID
     * @param $type     string 对象类型（例如 证件管理、稽核记录等）
     * @param $power    string 权限
     * @param $formName string 表单名称
     * @return string
     */
    public static function addFileComponent(string $id, string $type, string $power, string $formName): string
    {
        /*******附件****************/
        $fileCollection = '';
        $result = find(array('table' => "file", 'where' => "targetId !='' and targetId = '{$id}' and target='{$type}' order by time asc"));
        foreach ($result['array'] as $array) {
            $size = self::formatSize($array['size']);
            $view = self::view($array['src'],false,$array['name']);
            $fileCollection .= "
                                    <div class='file_block_bg'>
                                    <img  src='" . root . "img/control/annex.svg'>
                                    <div class='file_block_right'><div class='file_block_right_text'>{$array['name']}({$size})</div>$view&emsp;<span class='del-row-button' onclick=\"delFile('{$array['id']}','{$power}',this)\">删除</span></div>
                            </div>
        ";
        }
        return "<div class='file_block_bg_parent'  ondragover=\"allowDrop(event)\" ondrop=\"pasteFile(event,'{$formName}',root+'control/adIndex.html?cla=fileUpload&fun=uploadFile&power={$power}','add-file-button','drop')\" onpaste=\"pasteFile(event,'{$formName}',root+'control/adIndex.html?cla=fileUpload&fun=uploadFile&power={$power}','add-file-button')\">{$fileCollection}<div id='add-file-button' onclick=\"$('[name={$formName}] #uploadFile').click();\" title='点击上传文件或粘贴复制的文件到框中' class='file_block_add_btn'>+</div></div>
                     <div class='hidden'><input name='fileType' value='{$type}'><input name='uploadFile' id='uploadFile' type='file' onchange=\"uploadAttachFile('{$formName}',root+'control/adIndex.html?cla=fileUpload&fun=uploadFile&power={$power}','add-file-button')\"></div>";
    }

    /**
     * 上传附件
     */
    public function uploadFile()
    {
        $file = $_FILES['uploadFile'] ?? [];
        $power = $this->get('power');
        $type = $this->post('fileType');
        if (!$this->power($power, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($type)) {
            $json['warn'] = '未找到上传的类型';
        } else {
            $result = $this->saveFile($file, $power, explode(',', para('fileFormat')));
            if (!$result['code']) {
                $json['warn'] = $result['warn'];
            } else {
                $field = array('id' => suiji(), 'stid' => $this->control['stid'], 'target' => $type, 'name' => $result['fileName'], 'format' => $result['suffix'], 'size' => $result['size'], 'src' => $result['src'], 'updateTime' => $this->time, 'time' => $this->time);
                $warn = insert(array('table' => 'file', 'field' => $field));
                if ($warn == '新增成功') {
                    $json['warn'] = 2;
                    $json['data']['id'] = $field['id'];
                    $json['data']['src'] = root . $field['src'];
                    $size = self::formatSize($field['size']);
                    $json['data']['html'] = "<div class='file_block_bg'>
                                                <img  src='" . root . "img/control/annex.svg'><input name='fileId[]' type='hidden' value='{$field['id']}' />
                                                <div class='file_block_right'><div class='file_block_right_text'>{$field['name']}({$size})</div><div class='del-row-button'  onclick=\"delFile('{$field['id']}','{$power}',this)\">删除</div></div>
                                        </div>";
                } else {
                    $json['warn'] = '上传失败';
                }
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 删除图片
     */
    public function uploadImg(): bool|string
    {
        $file = $_FILES['uploadImg'];
        $power = $this->get('power');
        $type = $this->post('imgType');
        if (!$this->power($power, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($type)) {
            $json['warn'] = '未找到上传的类型';
        } else {
            $result = $this->saveFile($file, $power, ['jpg', 'jpeg', 'png', 'gif']);
            if (!$result['code']) {
                $json['warn'] = $result['warn'];
            } else {
                $field = array('id' => suiji(), 'stid' => $this->control['stid'], 'target' => $type, 'name' => $result['fileName'], 'format' => $result['suffix'], 'size' => $result['size'], 'src' => $result['src'], 'updateTime' => $this->time, 'time' => $this->time);
                $warn = static::insert(array('table' => 'file', 'field' => $field));
                if ($warn == '新增成功') {
                    $json['warn'] = 2;
                    $json['data']['id'] = $field['id'];
                    $json['data']['src'] = root . $field['src'];
                    $root = root;
                    $json['data']['html'] = <<<efo
<li><input name='imgId[]' type='hidden' value='{$field['id']}' /><img class="li-ico" alt="" src="{$root}{$field['src']}"><a onclick="del_img('{$field['id']}','{$power}',this)" href='javascript:void(0)'><div><span class='u-icon-delete'><i></i></span></div></a></li>
efo;
                } else {
                    $json['warn'] = $warn;
                }
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 删除附件
     *
     * @return bool|string
     */
    public function delFile()
    {
        $power = $this->post('power');
        $file = query("file", " id = '" . $this->post('id') . "' ");
        if (!$this->power($power, 'edit')) {
            $json['warn'] = '你还没有编辑的权限';
        } elseif (empty($file['id'])) {
            $json['warn'] = '没有找到此文件';
        } else {
            $warn = delete(array('table' => 'file', 'where' => " id = '$file[id]'"));
            if ($warn == '删除成功') {
                fileDelete($file['src']);
                $json['warn'] = 2;
            } else {
                $json['warn'] = "删除失败";
            }
        }
        return json_encode($json, 320);
    }


    /**
     * 文件列表展示
     *
     * @param string $id 对象ID
     * @param string $type 对象类型
     * @return string
     */
    public static function showFile(string $id, $type = ''): string
    {
        $where = '';
        if ($type) {
            $where .= " and target = '$type'";
        }
        $fileCollection = '';
        $result = find(array('table' => " file", "where" => "targetId !='' and targetId = '$id' {$where} order by time asc"));
        foreach ($result['array'] as $array) {
            $size = self::formatSize($array['size']);
            $fileCollection .= "
        <div class='file_block_bg'>
                <img src='" . root . "img/control/annex.svg'>
                <div class='file_block_right'><div class='file_block_right_text'>{$array['name']}({$size})</div><div>" . self::view($array['src'], true, $array['name']) . "</div></div>
        </div>
        ";
        }
        return $fileCollection ? "<div class='file_block_bg_parent'>" . $fileCollection . "</div>" : '';
    }

    /**
     * 图片列表展示
     *
     * @param string $id 对象ID
     * @param string $type 对象类型
     * @return string
     */
    public static function showImg($id, $type = ''): string
    {
        $root = root;
        $where = '';
        if ($type) {
            $where .= " and target = '$type'";
        }
        $fileCollection = '';
        $result = find(array('table' => " file", "where" => "targetId !='' and targetId = '$id' {$where} order by time asc"));
        foreach ($result['array'] as $array) {
            if (in_array($array['format'], ['jpg', 'jpeg', 'png', 'gif']))
                $fileCollection .= <<<efo
<li><a target="_blank" href="{$root}{$array['src']}"><img alt="" src="{$root}{$array['src']}"></a></li>
efo;
        }
        return $fileCollection ? "<div class='img-list'><ul class='img-ul'>" . $fileCollection . "</ul></div>" : '';
    }

    /**
     * 预览及下载
     *
     * @param string $src 文件地址
     * @param false $download 下载按钮
     * @param string $fileName 下载文件名称
     * @return string
     */
    public static function view(string $src, $download = false, $fileName = ''): string
    {
        $html = '';
        if (file_exists(serverRoot . $src)) {
            $suffix = self::getExtension($src);
            if (in_array($suffix, ['xlsx', 'pptx', 'ppt', 'xls', 'doc', 'docx'])) {
                $url = self::wpsView(['name' => $fileName, 'href' => $src, 'format' => $suffix]);
                $html .= "\n<a target='_blank' href='" . $url . "' title='预览' class='del-row-button'>预览</a>";
            } elseif (in_array($suffix, ['jpg', 'png', 'jpeg', 'pdf', 'gif', 'bmp'])) {
                $url = root . $src;
                $html .= "\n<a target='_blank' href='" . $url . "' title='预览' class='del-row-button'>预览</a>";
            }
            if ($download) {
                $url = root . $src;
                $html .= "\n<a target='_blank' download='{$fileName}' href='" . $url . "' title='下载' class='del-row-button'>下载</a>";
            }
        }
        return $html;
    }

    /*
    wps文件预览
    $data = array(
        "format" => "文件格式，如doc,xls",
        "name" => "文件名称",
        "href" => "文件跟目录路径",
    );
    */
    public static function wpsView($data)
    {
        $format = '';
        //参数准备
        $wpsAppKey = '40bbc55d144c46e1996d0c7a1c5a5a46';
        $para = array(
            "_w_appid" => '1f3e2c82c20348b390460f6235f164d2',
            "_w_userid" => self::$stid,
            "_w_fileId" => md5(root . $data['href']),
            "_w_name" => $data['name'],
            "_w_filepath" => root . $data['href'],
        );
        //判断文件类型
        $formatArray = array(
            "w" => array("doc", "docx"),
            "s" => array("xls", "xlsx"),
            "p" => array("ppt", "pptx"),
            "f" => array("pdf"),
        );
        foreach ($formatArray as $key => $value) {
            if (in_array($data['format'], $value)) {
                $format = $key;
            }
        }
        //按照键名对数组升序排序
        ksort($para);
        //生成签名字符串
        $get = $str = "";
        foreach ($para as $key => $value) {
            $str .= $key . "=" . $value;
            $get .= $key . "=" . $value . "&";
        }
        $str .= "_w_secretkey=" . $wpsAppKey;
        //签名
        $sign = hash_hmac('sha1', $str, $wpsAppKey, true);
        $sign = base64_encode($sign);
        $sign = urlencode($sign);
        $get .= "_w_signature=" . $sign;
        //生成URL
        return "https://wwo.wps.cn/office/" . $format . "/" . $para['_w_fileId'] . "?" . $get;
        //返回
    }
}
